<?php
/**
 * @author Eugenio Fage
 * http://eugeniofage.wordpress.com/
 * http://code.google.com/p/monky/
 * 
 */
class LogsController extends AppController {
	
	var $name = 'Logs';
	var $uses=array('Log','User','Link','Comment');
	
	
	function index(){
		$logs=$this->Log->find('all',array(
			'recursive'=>-1,
			'conditions'=>array('Log.type'=>array('link_new','comment_new','link_publish')),
			'limit'=>20,
			'order'=>'Log.id DESC'
		));

		$parsedLogs=array();
		foreach ($logs as $l){
			$parsedLogs[]=$this->_parseLog($l['Log']);
		}
		$this->set('Logs',$parsedLogs);
	}	
	
	function _parseLog($log){
		return $this->{'_parseLog_'.$log['type']}($log);
	}
	
	function _parseLog_link_new($log){
		$link=$this->_getLinkData($log['ref_id']);
		$who=$this->_getUserData($log['user_id']);
		$action=__('New link',true);
		$date=$log['created'];
		$status=$link['status'];
				
		return compact('date','action','link','who','status');
	}
	
	function _parseLog_comment_new($log){
		$link=$this->_getLinkData($log['ref_id']);
		$comment=array('id'=>$log['extradata']);
		$who=$this->_getUserData($log['user_id']);
		$action=__('New comment',true);
		$date=$log['created'];
		$status=$link['status'];
		
		return compact('date','action','link','who','status','comment');
	}

	function _parseLog_link_publish($log){
		$link=$this->_getLinkData($log['ref_id']);
		$action=__('Link publish',true);
		$date=$log['created'];
		$status=$link['status'];
		
		return compact('date','action','link','status');
	}
	
	function _getLinkData($id){
		$link=$this->Link->find('first',array(
			'fields'=>array('Link.id','Link.title','Link.status'),
			'conditions'=>array('Link.id'=>$id),
			'recursive'=>-1
		));
		
		return $link['Link'];
	}
	
	function _getUserData($id){
		$user=$this->User->find('first',array(
			'fields'=>array('User.id','User.username'),
			'conditions'=>array('User.id'=>$id),
			'recursive'=>-1
		));
		
		return $user['User'];
	}
	
}